package com.vinoxm.rss.subscribe.vo;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

@Log4j2
public class SubscribeBase {

    private static final SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);

    public static boolean checkRegex(String[] regex, Item item) {
        int flag = 0;
        for (String reg : regex) {
            if (Pattern.matches(reg, item.getTitle())) {
                flag++;
            }
        }
        return flag == regex.length;
    }

    @Data
    public static class Rss {
        private Channel channel;
    }

    @Data
    public static class SingleRss {
        private SingleChannel channel;
    }

    @Data
    public static class Channel {
        private List<Item> item;
        private String link;
        private String description;
        private String language;
        private String title;
    }

    @Data
    public static class SingleChannel {
        private Item item;
    }

    public static class Item {
        @Getter
        @Setter
        private Enclosure enclosure;
        @Getter
        @Setter
        private String author;
        @Getter
        @Setter
        private String link;
        @Getter
        @Setter
        private String description;
        @Getter
        @Setter
        private String title;

        @Setter
        private String pubDate;

        public Date getPubDate() {
            Date result;
            try {
                result = format.parse(pubDate);
            } catch (ParseException | NumberFormatException e) {
                log.error(e.getCause() + e.getMessage() + pubDate);
                result = null;
            }
            return result;
        }
    }

    @Data
    public static class Enclosure {
        private Integer length;
        private String type;
        private String url;
    }
}
